<?php
declare (strict_types = 1);

namespace app\command;

use app\model\DistributorsSharingStatistics;
use app\model\PayRecord;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class DistributorsSharingTask extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('distributors-sharing-task')// 配置一个参数
            ->addArgument('date_str', Argument::OPTIONAL, '当天时间')
            ->setDescription('分销商分成数据每日统计(每天凌晨统计昨天的数据)');
    }

    protected function execute(Input $input, Output $output)
    {
        $dateStr = $input->getArgument('date_str');
        if ($dateStr){
            $dateTime = date('Ymd', strtotime($dateStr));
            $month = date('Ym', strtotime($dateStr));
        }else{
            $dateTime = date('Ymd', time() - 86400);
            $month = date('Ym', time() - 86400);
        }

        $doneTaskCount = DistributorsSharingStatistics::where('date',$dateTime)->count();
        //任务已经跑过
        if ($doneTaskCount > 0){
            return 0;
        }
        $distributor = Db::name('responsibility_person')->where(['is_distributor' => 1])->field('id, name, commission_scale, scale, company_id,wechat_applet_commission_scale')->select()->toArray();
        $pids = array_column($distributor, 'id');
        $pitcher = Db::name('responsibility_person')->where(['pid' => $pids])->field('id, pid')->select()->toArray();

        $pitcherIds = array_column($pitcher, 'id');

        $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

        $linkIds = array_column($linkData, 'id');

        $distributorArray = [];
        foreach ($pitcher as $item) {
            $distributorArray[$item['pid']][] = $item['id'];
        }
        $link = [];
        foreach ($linkData as $value) {
            $link[$value['responsibility_person_id']][] = $value['id'];
        }

        $distributorData = [];
        foreach ($distributorArray as $key => $value) {
            $linkIdArray = [];
            foreach ($value as $pitcherId) {
                if (!empty($link[$pitcherId])) {
                    $linkIdArray = array_merge($linkIdArray, $link[$pitcherId]);
                }
            }
            $distributorData[$key] = $linkIdArray;
        }

        if ($dateStr){
            $date = date('Y-m-d', strtotime($dateStr));
        }else{
            $date = date('Y-m-d', time() - 86400);
        }
        $startTime = strtotime($date);
        $endTime = strtotime($date . ' 23:59:59');
        $where = [
            ['status', '=', 1],
            ['pay_time', '>=', $startTime],
            ['pay_time', '<=', $endTime],
            ['link_id', 'in', $linkIds]
        ];

        $payData = Db::name('pay_record')->where($where)->field('link_id, total_fee, pay_merchant, device_type')->select()->toArray();
        $rechargeData = [];
        $virtualRechargeData = [];
        $commonRechargeData = [];
        foreach ($payData as $value) {
            $rechargeData[$value['link_id']][] = $value['total_fee'];
            if ($value['pay_merchant'] == PayRecord::PAY_MERCHANT_VIRTUALPAYMENT && $value['device_type'] == PayRecord::DEVICE_TYPE_ANDROID){
                $virtualRechargeData[$value['link_id']][] = $value['total_fee'];
            }else{
                $commonRechargeData[$value['link_id']][] = $value['total_fee'];
            }
        }

        // 退款金额
        $where = [
            ['rr.status', '=', 1],
            ['rr.refund_time', '>=', $date.' 00:00:00'],
            ['rr.refund_time', '<=', $date.' 23:59:59']
        ];
        $refundData = Db::name('refund_record')->alias('rr')->leftjoin('pay_record pr', 'pr.id = rr.pay_id')->where($where)->field('rr.link_id, rr.refund_price, rr.pay_merchant, pr.device_type')->select()->toArray();
        $refund = [];
        $virtualRefund = [];
        $commonRefund = [];
        foreach ($refundData as $key => $value) {
            $refund[$value['link_id']][] = $value['refund_price'];
            if ($value['pay_merchant'] == PayRecord::PAY_MERCHANT_VIRTUALPAYMENT && $value['device_type'] == PayRecord::DEVICE_TYPE_ANDROID){
                $virtualRefund[$value['link_id']][] = $value['refund_price'];
            }else{
                $commonRefund[$value['link_id']][] = $value['refund_price'];
            }
        }

        // 统计分销商充值以及分成、手续费
        $distributorResult = array_column($distributor, NULL, 'id');

        $saveData = [];

        foreach ($distributorData as $distributorId => $linkId) {
            $rechargePrice = 0;
            $refundPrice = 0;
            $virtualRechargePrice = 0;
            $virtualRefundPrice = 0;
            $commonRechargePrice = 0;
            $commonRefundPrice = 0;

            foreach ($linkId as $id) {
                $rechargePrice += !empty($rechargeData[$id]) ? array_sum($rechargeData[$id]) : 0;
                $virtualRechargePrice += !empty($virtualRechargeData[$id]) ? array_sum($virtualRechargeData[$id]) : 0;
                $refundPrice += !empty($refund[$id]) ? array_sum($refund[$id]) : 0;
                $virtualRefundPrice += !empty($virtualRefund[$id]) ? array_sum($virtualRefund[$id]) : 0;
                $commonRechargePrice += !empty($commonRechargeData[$id]) ? array_sum($commonRechargeData[$id]) : 0;
                $commonRefundPrice += !empty($commonRefund[$id]) ? array_sum($commonRefund[$id]) : 0;
            }
            //非虚拟支付手续费
            $commonCommission = round(($commonRechargePrice - $commonRefundPrice) * $distributorResult[$distributorId]['commission_scale'] / 100, 2);
            //虚拟支付手续费
            $virtualCommission = round(($virtualRechargePrice - $virtualRefundPrice) * $distributorResult[$distributorId]['wechat_applet_commission_scale'] / 100, 2);
            //总手续费
            $commission =  round($commonCommission+$virtualCommission,2);
            //非虚拟支付分成比率
            $scale = round((1 - $distributorResult[$distributorId]['scale'] / 100), 2);
            //非虚拟支付分成金额
            $commonSharingAmount = round(($commonRechargePrice - $commonRefundPrice - $commonCommission) * $scale, 2);
            //虚拟支付分成比率
            $virtualScale = config('distributor_setting.virtual_scale');
            //虚拟支付分成金额
            $virtualSharingAmount = round(($virtualRechargePrice - $virtualRefundPrice - $virtualCommission) * $virtualScale, 2);
            //分销商总分成金额
            $sharingAmount = round($commonSharingAmount+$virtualSharingAmount, 2);
            //腾讯虚拟支付通道费-算到比翼鸟成本
            $virtualCommissionCostByLiuyi = round(($virtualRechargePrice - $virtualRefundPrice) * 0.1 ,2);
            //虚拟支付比翼鸟分成 = （虚拟充值-退款）*0.2-虚拟支付通道费
            $virtualLySharingAmount = ($virtualRechargePrice - $virtualRefundPrice) * 0.2 - $virtualCommissionCostByLiuyi;
            //非虚拟支付比翼鸟分成金额=非虚拟充值-退款-千8通道费）*0.15
            $commonLySharingAmount = ($commonRechargePrice - $commonRefundPrice  - $commonCommission) * 0.15;

            //比翼鸟分成金额
            $lySharingAmount = round($virtualLySharingAmount + $commonLySharingAmount,2);
            //round($rechargePrice - $refundPrice - $sharingAmount - $commission - $virtualCommissionCostByLiuyi, 2);

            $saveData[] = [
                'date' => $dateTime,
                'month' => $month,
                'name' => $distributorResult[$distributorId]['name'],
                'distributor_id' => $distributorId,
                'company_name' => Db::name('company')->where('id', $distributorResult[$distributorId]['company_id'])->field('name')->find()['name'],
                'recharge_price' => round($rechargePrice, 2),
                'refund_price' => round($refundPrice, 2),
                'commission' => $commission,
                'scale' => $scale,
                'sharing_amount' => $sharingAmount,
                'ly_sharing_amount' => $lySharingAmount,
                'virtual_recharge_price' => round($virtualRechargePrice, 2),
                'virtual_refund_price' => round($virtualRefundPrice, 2),
                'virtual_commission' => $virtualCommission,
                'virtual_scale' => $virtualScale,
                'common_recharge_price' => round($commonRechargePrice, 2),
                'common_refund_price' => round($commonRefundPrice, 2),
                'common_scale' => $scale,
                'ad_incentive_amount' => round(($virtualRechargePrice - $virtualRefundPrice) * 0.05, 2),
                'virtual_amount' => $virtualSharingAmount,
                'common_amount' => $commonSharingAmount,
                'common_commission' => $commonCommission,
                'created_at' => time(),
            ];
        }

        $bool = Db::name('distributors_sharing_statistics')->insertAll($saveData);
        return $bool;
    }
}
